package org.jsg1904.study001.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: 默苍璃
 * @date: 2022-02-10 14:54
 * <p>
 * 自定义登录成功处理器
 * <p>
 * ForwardAuthenticationSuccessHandler内部就是最简单的请求转发。由于是请求转发，当
 * 遇到需要跳转到站外或在前后端分离的项目中就无法使用了。
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private String url;

    public MyAuthenticationSuccessHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        // 获取id地址
        System.out.println(request.getRemoteAddr());

        User user = (User) authentication.getPrincipal();
        System.out.println(user.getUsername());
        // 处于安全考虑输出 为 null
        System.out.println(user.getPassword());
        System.out.println(user.getAuthorities());

        response.sendRedirect(url);
    }

}
